<template>
  <div class = "nav">
    <div class = 'weather'>
      <el-popover
          placement="top-start"
          width="300"
          trigger="hover">
          <el-table :data="threeDays">
            <el-table-column width="100" property="date" label="日期"></el-table-column>
            <el-table-column width="100" property="type" label="天气"></el-table-column>
            <el-table-column width="100" property="temperature" label="温度"></el-table-column>
          </el-table>
          <div class = "left" slot="reference"><p>{{ time }}&nbsp;&nbsp;&nbsp;{{ city }}</p><p>{{ date }}{{ weekday }}&nbsp;&nbsp;{{ weather }}</p></div>
      </el-popover>
    </div>
    <div class = "upload">
      <el-upload
        class="upload-demo"
        action=""
        :on-change="handleChange"
        :on-exceed="handleExceed"
        :on-remove="handleRemove"
        
        :limit="2"
        accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
        :auto-upload="false">
        <el-tooltip content="注意：只能上传xlsx/xls文件" placement="left" effect="light">
          <el-button size="small" type="info" @click = "disabled = !disabled">点击上传</el-button>
        </el-tooltip>
      </el-upload>
    </div>
    <div class = "select">
       <el-select v-if = "switchIcon" v-model="search" filterable placeholder="请输入中国省市自治区" @change = "selectValue" size = "small">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-autocomplete
        v-else
        size = "small"
        popper-class="my-autocomplete"
        v-model="inputName"
        :fetch-suggestions="querySearch"
        placeholder="请输入内容"
        @select = "handleSelect">
        <i
          class="el-icon-edit el-input__icon"
          slot="suffix">
        </i>
        <template slot-scope="{ item }">
          <div class="name">{{ item.value }}</div>
          <span class="addr">{{ item.address }}</span>
        </template>
      </el-autocomplete>
      <el-button style = "margin-left:2%;" type="info" icon="el-icon-refresh" size = "mini" circle @click = "switchInput" title = "点我可以切换搜索方式哦~"></el-button>
    </div>
    <div class = "head">
      <el-dropdown @command ="handleCommand">
        <img src="../assets/touxiang.png" alt="头像加载失败">
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command = "a" icon = "el-icon-switch-button">退出登录</el-dropdown-item>
          <el-dropdown-item command = "b" icon = "el-icon-files">上传记录</el-dropdown-item>
          <el-dropdown-item command = "c" icon = "el-icon-reading">使用指南</el-dropdown-item>
          <el-dropdown-item command = "d" icon = "el-icon-download">下载模板</el-dropdown-item>
          <el-dropdown-item command = "e" icon = "el-icon-collection">意见反馈</el-dropdown-item>
          <el-dropdown-item command = "f" icon = "el-icon-tickets">导出数据</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <canvas id = "weather"></canvas>
   
  </div>
</template>

<script>
import axios from 'axios';
import bus from '../utils/eventBus';
import allProvinces from '../utils/province';
import {getCurrentTime , getCurrentDate , getCurrentWeek} from '../utils/time'
import {snow , rain } from '../utils/weather'

axios.defaults.headers.post['Content-Type'] = 'application/json';

export default {
   name:'Navigator',
   data(){
       return {
           switchIcon:true, //默认展示按照地区搜索，否则按照人名搜索
           inputName:'',   //输入姓名
           names:[],
           disabled:false,
           address:'',
           city:'',
           weather:'',
           time:'',
           date:'',
           weekday:'',
           threeDays:[],
           search:'',
           options: [],
           fileList:[],
           timer1:'',
           timer2:'',
           timer3:'',
       }
   },
   created(){
      this.getAddress();
      this.options = allProvinces;
      this.getAllNames();
      this.getCurrent();
      this.getCurrentWeekday();
      this.getThree();
      this.getThreeWeather();
   },

   beforeDestory(){
      clearInterval(this.timer1);
      clearInterval(this.timer2);
      clearInterval(this.timer3);
      clearInterval(this.timer4);
   },
  
   methods:{
      getAddress: function(){      // 定位当前所在位置
         let ip = returnCitySN["cip"];
         this.$axios.get('/bbb/location/ip?ak=1weYccRbkZdkmWxZL6wDuuj04TzYt7Go&ip='+ip).then(res => {
           let that = this;
           console.log(res);
           that.address = res.data.content.address;
           that.city = res.data.content.address_detail.city;
           that.getWeather(res.data.content.address_detail.city);
         },err => {
           console.log('ERROR: ' + err);
         })
      },

      getThree(){      // 实时获取日期
          let that = this;
          that.timer3 = setInterval(() => {
            that.date = getCurrentDate(0,new Date());
          },1000)
      },

      getThreeWeather(){  // 实时获取天气
         let that = this;
         that.timer4 = setInterval(() => {
           that.getWeather();
         },1000*60*60)
      },

      getCurrent(){     // 实时获取时间
        let that = this;
        that.timer1 = setInterval(() => {
          that.time =  getCurrentTime(new Date());
        },1000)
      },

      getCurrentWeekday(){    // 实时获取星期
        let that = this;
        that.timer2 = setInterval(() => {
          that.weekday =  getCurrentWeek(new Date());
        },1000)
      },

      getWeather:function(pro){    // 获取本地天气
         this.$axios.get('http://wthrcdn.etouch.cn/weather_mini?city=' + pro).then(res => {
           console.log(res);
           let canvas = document.getElementById('weather');
           this.weather = res.data.data.forecast[0].type;
           if(this.weather.includes('雪')){
             snow(canvas);
           }
           if(this.weather.includes('雨')){
             rain(canvas);
           }
           this.threeDays = [];
           res.data.data.forecast.forEach((item,index) => {
             if(index == 1 || index == 2 || index == 3){
                let low = item.low.split(' ')[1];
                let high = item.high.split(' ')[1];

                item.temperature = `${low}/${high}`;

                this.threeDays.push(item);
             }
           })

           console.log(this.threeDays);
         },err => {
           console.log('ERROR: ' + err);
         })
      },

      selectValue(e){     // 利用bus传递搜索框的值
         bus.$emit('search', e);
      },
      
      handleChange(file){
        this.uploadFile(file.raw);
        this.importExcel(file.raw);
      },

      handleRemove(file){
         console.log(file);
         let uid = file.uid;
         let filelist = this.fileList;
         let len = filelist.length;
         for(let i = 0;i < len;i++){
           if(filelist[i]['uid'] == uid){
             this.fileList.splice(i,1);
           }
         }

         console.log(this.fileList);
         
      },

      handleSuccess(file){     // 注意：这个上传成功必须写在回调函数里面
        console.log(file);
        this.$message({
          type:'success',
          message:`${file.name}上传成功`
        })
      },

      handleExceed(){
        this.$message({
          type:'warning',
          message:'超出上传数量！'
        })
      },

      uploadFile(file){      // 存入上传记录
        const formData = new FormData();
        const email = localStorage.getItem('email');
        const time = new Date();
        formData.append('files.type', file, `${time.getTime()}`);
        formData.append('data', JSON.stringify({ name: file.name,uploadBy: email }));

        this.$axios.post('http://119.91.81.28:1337/file-lists',formData).then(res => {
          console.log(res);
        },err => {
          console.log(err);
        })
      },

      importExcel(file){   //导入excel
        console.log(file);

        let _this = this;
        let email = localStorage.getItem('email');
        // 通过DOM取文件数据
        this.file = file;
        var rABS = false; //是否将文件读取为二进制字符串
        var f = this.file;
        var flag = false;
        var reader = new FileReader();
        //if (!FileReader.prototype.readAsBinaryString) {
        FileReader.prototype.readAsBinaryString = function(f) {
            var binary = "";
            var rABS = false; //是否将文件读取为二进制字符串
            var pt = this;
            var wb; //读取完成的数据
            var outdata;
            var reader = new FileReader();
            reader.onload = function(e) {
            var bytes = new Uint8Array(reader.result);
            var length = bytes.byteLength;
            for(var i = 0; i < length; i++) {
                binary += String.fromCharCode(bytes[i]);
            }
            var XLSX = require('xlsx');
            if(rABS) {
                wb = XLSX.read(btoa(fixdata(binary)), { //手动转化
                    type: 'base64'
                });
            } else {
                wb = XLSX.read(binary, {
                    type: 'binary'
                });
            }
            outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);//outdata就是你想要的东西
                this.da = [...outdata];
                let len = this.da.length;
                this.da.map((v,i) => {
                    let obj = {}
                    obj.name = v['姓名'].trim();
                    obj.sex = v['性别'].trim();
                    obj.graduate = v['毕业年级'] + '';
                    obj.phone = v['电话'] + '';
                    obj.college = v['学校'].trim();
                    obj.province = v['省份'].trim();
                    obj.downtown = v['市区'].trim();
                    obj.createdBy = email;

                    console.log(obj);

                    let p = new Map();
                    let temp = 1;

                    _this.$axios.get('http://119.91.81.28:1337/students').then(res => {
                      res.data.forEach(item => {
                        p.set(item.id,item.phone);
                      })

                      for(let [key,value] of p.entries()){
                        if(value == obj.phone){
                          temp = 0;
                          _this.$axios.put(`http://119.91.81.28:1337/students/${key}`,obj).then(res => {
                              console.log(res);
                          })
                        }
                      }

                      if(temp == 1){
                        _this.$axios.post('http://119.91.81.28:1337/students',JSON.stringify(obj)).then(res => {
                          console.log(res);
                          if(len == i+1){
                            _this.handleSuccess(file);
                          }
                        })
                      }
                    })
                   
                })
            }
            
            reader.readAsArrayBuffer(f);
        }
        
        if(rABS) {
            reader.readAsArrayBuffer(f);
        } else {
            reader.readAsBinaryString(f);
        }

      },

      downloadTemplate(){   //导出excel模板
          require.ensure([], () => {
            const { export_json_to_excel } = require('../utils/excel/Export2Excel.js')
            const tHeader = ['姓名', '性别','毕业年级','电话','学校','省份','市区'];
            const filterVal = ['name', 'sex','graduate','phone','college','province','downtown'];
            const list = [];
            const data = this.formatJson(filterVal, list);
            this.$prompt('请输入','添加导出excel文件名',{
              confirmButtonText: '确定',
              cancelButtonText: '取消'
            }).then(res => {
              export_json_to_excel(tHeader, data, res.value);
            })
            
          })
      },

      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      },

      handleCommand(item){
        switch (item){
          case 'a':
            let storage = localStorage;
            storage.clear();
            this.$router.push({
             name:'login'
            })
            break;
          case 'b':
            this.$router.push({
             name:'records'
            })
            break;
          case 'c':
            // this.drawer = true;
            bus.$emit('drawer',true);
            break;
          case 'd':
            this.downloadTemplate();
            break;
          case 'e':
            window.open('https://support.qq.com/product/354384','_blank');
            break;
          case 'f':
            this.$router.push({
             name:'exportData'
            })
            break;
        }
        
      },

      switchInput(){        // 搜索方式切换
        this.switchIcon = !this.switchIcon;
      },

      getAllNames(){
        let email = localStorage.getItem('email');
        this.$axios.get(`http://119.91.81.28:1337/students?createdBy=${email}`).then(res => {
          console.log(res);
          res.data.forEach(item => {
            this.names.push({"value":`${item.name}`,"address":`${item.graduate}年 ${item.college}`,"info":item})
          })

        },err => {
          console.log(err);
        })
      },

      querySearch(queryString, cb) {
        var names = this.names;
        queryString = queryString.trim();
        var results = queryString ? names.filter(this.createFilter(queryString)) : names;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },

      createFilter(queryString) {
        return (name) => {
          return name.value.toLowerCase().includes(queryString.toLowerCase());
        };
      },

      handleSelect(item){    // 选取的某个数据
        bus.$emit('searchByName',item);
      }

   }
}
</script>

<style>
.nav{
  width:100%;
  height:12vh;
  display: flex;
  justify-content: space-around;
  align-items: center;
  opacity: 0.9;
  filter: alpha(opacity=90);
  /* background-color: lightgray;  */
}
.nav canvas{
  z-index: -1;
  pointer-events: none;
  position: absolute;
}
.nav .weather{
  width:20vw;
  height:8vh;
  text-align:center;
  display: flex;
  flex-direction: row;
  position:relative;
  /* line-height:8vh; */
}
.nav .weather .left{
  margin-top:-2vh;
  margin-left:3vw;
  width:8vw;
  height:8vh;
}
.nav .weather .left p{
  color:aliceblue;
}
.nav .weather .left p:nth-child(1){
   font-size: 16px;
   margin-left:-0.2vw;
}
.nav .weather .left p:nth-child(2){
   margin-top:-2vh;
   font-size: 5px;
   transform: scale(0.4);
}
.nav .upload{
  margin-top:5%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  /* align-items: center;  */
  width:15vw;
  height:15vh;
  z-index: 999;
}
.nav .select{
  display: flex;
  align-items: center;
  width:15vw;
  height:8vh;
}
.my-autocomplete li {
  line-height: normal;
  padding: 7px;
}
.my-autocomplete li .name {
  text-overflow: ellipsis;
  overflow: hidden;
}
.my-autocomplete li .addr {
  font-size: 12px;
  color:lightslategray;
  text-overflow: ellipsis;
  overflow: hidden;
}
.my-autocomplete li .highlighted .addr {
  color: #ddd;
}
.nav .head a{
  text-decoration: none;
}
</style>